﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SMS.Windows.Forms;
using System.Linq;
using LibraryONTrack.dao;
using LibraryONTrack.dto;
using LibraryONTrack.BAL;

namespace LibraryONTrack.UI
{
	public partial class AddBookPage : SMS.Windows.Forms.InteriorWizardPage
	{
		private int currentTeacherIndex = -1;
		private int currentStudentIndex = -1;
		private int currentBookIndex = -1;
		private bool _skipValidation;
		private OverdueBookManager obm = null;

		public AddBookPage()
		{
			InitializeComponent();
		}

		protected override bool OnSetActive()
		{
			if (!base.OnSetActive())
				return false;

			// Enable both the Next and Back buttons on this page    
			Wizard.SetWizardButtons(WizardButton.Back | WizardButton.Next);
			return true;
		}

		private void AddBookPage_Load(object sender, EventArgs e)
		{
			obm = new OverdueBookManager();

			TeacherComboBox.DataSource = new BindingList<Roster>(obm.RosterManager.GetAll());
			TeacherComboBox.DisplayMember = "Teacher";

			BookTitleComboBox.DataSource = new BindingList<Book>(obm.BookManager.GetAll());
  
		}

		private void TeacherComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			currentTeacherIndex = TeacherComboBox.SelectedIndex;
			Roster roster = (Roster)TeacherComboBox.SelectedItem;
			StudentComboBox.DataSource = new BindingList<Student>(roster.Students);
			if (roster.Students.Count > 0)
			{
				currentStudentIndex = 0;
			}
			else
			{
				currentStudentIndex = -1;
				StudentComboBox.Text = "";
			}
		}

		private void TeacherComboBox_Validating(object sender, CancelEventArgs e)
		{
			if (!_skipValidation)
			{
				string newTeacherName = TeacherComboBox.Text.Trim();
				if (!String.IsNullOrEmpty(newTeacherName))
				{
					BindingList<Roster> teachersBindingList = (BindingList<Roster>)TeacherComboBox.DataSource;
					if (teachersBindingList.FirstOrDefault(p => p.Teacher.Name == newTeacherName) == null)
					{
						if (MessageBox.Show(this,
																String.Format("Really create roster for new teacher '{0}?'",
																	newTeacherName),
																"Add New Teacher",
																MessageBoxButtons.YesNo,
																MessageBoxIcon.Question,
																MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)
						{
							teachersBindingList.Add(obm.RosterManager.AddRoster(newTeacherName));
							TeacherComboBox.SelectedIndex = teachersBindingList.Count - 1;

							// Fire off the event manually as windows will not if you write the same value that is already there
							TeacherComboBox_SelectedIndexChanged(TeacherComboBox, null);
						}
						else
						{
							TeacherComboBox.Text = "";
							TeacherComboBox.SelectedIndex = currentTeacherIndex;
							TeacherComboBox.Focus();
						}
					}
				}
			}

		}

		private void StudentComboBox_Validating(object sender, CancelEventArgs e)
		{
			if (!_skipValidation)
			{
				string newStudentName = StudentComboBox.Text.Trim();
				if (!String.IsNullOrEmpty(newStudentName))
				{
					BindingList<Student> studentBindingList = (BindingList<Student>)StudentComboBox.DataSource;
					if (studentBindingList.FirstOrDefault(p => p.Name == newStudentName) == null)
					{
						if (MessageBox.Show(this,
																String.Format("Really add new student '{0}' to '{1}' roster?",
																	newStudentName,
																	TeacherComboBox.Text),
																"Add New Student",
																MessageBoxButtons.YesNo,
																MessageBoxIcon.Question,
																MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)
						{
							try
							{
								studentBindingList.Add(obm.RosterManager.AddRosterStudent((Roster)TeacherComboBox.SelectedItem, newStudentName));
								StudentComboBox.Text = newStudentName;
								return;
							}
							catch (RosterManagerAssignedToAnotherException ex)
							{
								MessageBox.Show(this,
																String.Format("{0}\nTeacher: {1}\n\nPlease correct roster conflict and then retry.", ex.Message, ex.Teacher.Name),
																"Add New Student",
																MessageBoxButtons.OK,
																MessageBoxIcon.Error);
							}
						}
						StudentComboBox.Text = "";
						StudentComboBox.SelectedIndex = currentStudentIndex;
						StudentComboBox.Focus();
					}
				}
			}
		}

		private void StudentComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			currentStudentIndex = StudentComboBox.SelectedIndex;
		}

		private void BookTitleComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{

		}

		private void BookTitleComboBox_Validating(object sender, CancelEventArgs e)
		{
			if (!_skipValidation)
			{
				string newBookTitle = BookTitleComboBox.Text.Trim();
				if (!String.IsNullOrEmpty(newBookTitle))
				{
					BindingList<Book> bookBindingList = (BindingList<Book>)BookTitleComboBox.DataSource;
					if (bookBindingList.FirstOrDefault(p => p.Title == newBookTitle) == null)
					{
						if (MessageBox.Show(this,
																String.Format("Really add new book\n\n'{0}'?",
																	newBookTitle),
																"Add New Book",
																MessageBoxButtons.YesNo,
																MessageBoxIcon.Question,
																MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)
						{
							bookBindingList.Add(obm.BookManager.AddBook(newBookTitle));
							BookTitleComboBox.Text = newBookTitle;
						}
						else
						{
							BookTitleComboBox.Text = "";
							BookTitleComboBox.SelectedIndex = currentBookIndex;
							BookTitleComboBox.Focus();
						}
					}
				}
			}

		}

		private void AddOverdueBookButton_Click(object sender, EventArgs e)
		{
			Book book = (Book) BookTitleComboBox.SelectedItem;
			Student borrower = (Student) StudentComboBox.SelectedItem;
			try
			{
				obm.AddOverdueBook(borrower, book);
			}
			catch (AssignedToAnotherUserOverdueBookManagerException ex)
			{
				if (MessageBox.Show(this,
														String.Format("{0}\n"+
																					"\n"+
																					"is currently checked out to"+
																					"\n"+
																					"\n{1}"+
																					"\n"+
																					"\nDo you want to explictly reassign to {2}?",
															book.Title,
															ex.Borrower.Name,
															borrower.Name),
														"Enter Overdue Book",
														MessageBoxButtons.YesNo,
														MessageBoxIcon.Stop,
														MessageBoxDefaultButton.Button2) == DialogResult.Yes)
				{
					obm.AddOverdueBook(borrower, book, ex.Borrower);
				}
			}
			BookTitleComboBox.Text = "";
			TeacherComboBox.Focus();
		}
	}
}
